package com.glsc.ngateway.platform.service.glres;

import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.common.utils.CommonUtils;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscResourceOperateLog;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemAuth;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.glres.GlscSystemFile;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.glres.GlscSystemFileRepository;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.utils.SpecificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class GlscSystemFileService {
    private List<String> allowFileTypeList = new ArrayList<>(Arrays.asList("jpg", "sql", "txt", "jpeg", "gif", "png", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"));

    @Resource
    private GlscSystemFileRepository glscSystemFileRepository;

    @Resource
    private UserService userService;

    @Value("${nas.path.zyfile}")
    String documentNasPath = "";

    @Resource
    private GlscResourceOperateLogService logService;

    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<GlscSystemFile> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";


        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<GlscSystemFile> page = glscSystemFileRepository.findAll(SpecificationUtil.buildSpecification(param, GlscSystemFile.class), pageable);
        return page;
    }

    /**
     * 根据系统id查找所有的对接方信息
     *
     * @param systemId
     * @return
     */
    public List<GlscSystemFile> listBySystemId(Integer systemId) {
        return glscSystemFileRepository.findAll(Example.of(GlscSystemFile.builder().systemId(systemId).build()));
    }


    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public GlscSystemFile findById(Integer id) {
        Optional<GlscSystemFile> optional = glscSystemFileRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @return
     */
    @Transactional
    public PlatformResponse<?> upload(MultipartFile file, Integer id, PlatformUserDto user) {
        GlscSystemFile systemFile = new GlscSystemFile();
        systemFile.setId(id);
//        if (Objects.nonNull(id)) {
//            Optional<GlscSystemFile> optional = glscSystemFileRepository.findById(id);
//            if (optional.isPresent()) {
//                systemFile.setId(optional.get().getId());
//            }
//        }
//        systemFile.setFileType(fileType);
        if (Objects.nonNull(file)) {

            String oFileName = file.getOriginalFilename();
            log.info("上传的文件名：" + oFileName);
            if (null == oFileName || oFileName.length() < 4) {
                return PlatformResponse.failedMsg("上传文件名不合法，文件名至少4个字符");
            }
            oFileName = CommonUtils.getFileNameFromPath(oFileName);//去除可能的文件路径（解决IE下带路径问题）

            int lastPos = oFileName.lastIndexOf(".");//lastPos=-1,没有文件类型后缀

            String fileSuffix = null;
            if (lastPos > 0 && lastPos < oFileName.length()) {
                fileSuffix = oFileName.substring(lastPos + 1).toLowerCase();
            }
            if (StrUtil.isEmpty(fileSuffix)) {
                fileSuffix = "";
            }
            fileSuffix = fileSuffix.toLowerCase();
            log.info("上传文件类型" + fileSuffix + "，文件全称：" + oFileName);
            if (!allowFileTypeList.contains(fileSuffix)) {
                return PlatformResponse.failedMsg("只能上传jpg/jpeg/gif/png/pdf/doc/xls/ppt类型的文件");
            }

            if (file.getSize() > 1024 * 1000 * 100) {
                return PlatformResponse.failedMsg("档案不得大于100M，实际上传文件大小为" + file.getSize() / (1000.0 * 1024));
            }

            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String path = documentNasPath + "systemResFile/" + time + "/" + uuid + "/" + oFileName;

            File destFile = new File(path);
            try {
                log.info("存储文件至目录" + destFile.getAbsolutePath());
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
            } catch (IOException e) {
                String errMsg = "上传产品档案失败，原因：" + e.getLocalizedMessage();
                log.error(errMsg, e);
                return PlatformResponse.failedMsg(errMsg);
            }
            systemFile.setFileName(oFileName);
            systemFile.setFilePath(path);
        }

//        systemFile.setSystemId(systemId);
//        systemFile.setMemo(memo);
        systemFile.setUserId(user.getId());
        systemFile.setUserName(user.getName());
        //systemFile.setSerialNo(UUID.randomUUID().toString());
        glscSystemFileRepository.save(systemFile);
        return PlatformResponse.successData(systemFile);
    }

    @Transactional
    public GlscSystemFile save(GlscSystemFile glscSystemFile) {
        Optional<GlscSystemFile> optional = glscSystemFileRepository.findById(glscSystemFile.getId());
        if (optional.isPresent()) {
            GlscSystemFile file = optional.get();
            if (Objects.nonNull(file) && StringUtils.isNotBlank(file.getFileType()) && StringUtils.isNotBlank(file.getFileDetailType())) {
                if (!glscSystemFile.getFileDetailType().equals(file.getFileDetailType()) || !glscSystemFile.getUserName().equals(file.getUserName())
                        || glscSystemFile.getFileName().equals(file.getFileName())
                        || glscSystemFile.getFilePath().equals(file.getFilePath())
                        || (StringUtils.isNotBlank(glscSystemFile.getMemo()) && StringUtils.isBlank(file.getMemo()))
                        || (StringUtils.isBlank(glscSystemFile.getMemo()) && StringUtils.isNotBlank(file.getMemo()))
                        || (StringUtils.isNotBlank(glscSystemFile.getMemo()) && StringUtils.isNotBlank(file.getMemo()) && !glscSystemFile.getMemo().equals(file.getMemo()))
                ) {
                    //2系统文档日志，3系统脚本清单日志
                    String dataType = "";
                    if (file.getFileType().equals("1")) {
                        dataType = "2";
                    } else {
                        dataType = "3";
                    }

                    logService.save(GlscResourceOperateLog.builder().deleted("N").memo(file.getMemo()).content("文件变更").
                            type("update_info").userId(file.getUserId()).userName(file.getUserName()).fileName(file.getFileName()).filePath(file.getFilePath())
                            .originalCreateTime(file.getCreateTime()).dataType(dataType).originalId(file.getId()).systemId(file.getSystemId()).build());
                }
            }


            file.setFileType(glscSystemFile.getFileType());
            file.setSystemId(glscSystemFile.getSystemId());
            file.setMemo(glscSystemFile.getMemo());
            file.setFileDetailType(glscSystemFile.getFileDetailType());
            file.setDeleted("N");
            file.setSourceType(glscSystemFile.getSourceType());
            return glscSystemFileRepository.save(file);
        }

        return null;
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Transactional
    public void delete(Integer id) {
        GlscSystemFile file = findById(id);
        //2系统文档日志，3系统脚本清单日志
        String dataType = "";
        if (file.getFileType().equals("1")) {
            dataType = "2";
        } else {
            dataType = "3";
        }

        logService.save(GlscResourceOperateLog.builder().deleted("N").memo(file.getMemo()).content("文件删除").
                type("delete_info").userId(file.getUserId()).userName(file.getUserName()).fileName(file.getFileName()).filePath(file.getFilePath())
                .originalCreateTime(file.getCreateTime()).dataType(dataType).originalId(file.getId()).systemId(file.getSystemId()).build());
        glscSystemFileRepository.deleteById(id);
    }
}
